package com.carryGo.web.hzl;

import com.carryGo.entity.PageManager;
import com.carryGo.entity.User;
import com.carryGo.service.hzl.UserService;
import com.carryGo.utils.dp.EncryptCodeUtils;
import com.carryGo.utils.hzl.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * ClassName:UserServlet
 * package:com.carryGo.web.hzl
 * Description:
 *
 * @Date:2020/8/24 14:39
 * @Author: tank_黄志凌
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {

    private UserService userService=new UserService();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method=request.getParameter("method");
        switch (method){
            case "toAdmin":
                WebUtils.toRequestPage(request,response,"admin");
                break;
            case "toShowUsers":
                WebUtils.toRequestPage(request,response,"showUsers");
                break;
            case "toAddUsers":
                WebUtils.toRequestPage(request,response,"addUsers");
                break;
            case "queryUsers":
                queryUsers(request,response);
                break;
            case "addUser":
                addUsers(request,response);
                break;
            case "delUser":
                delUsers(request,response);
                break;
            case "updateUsers":
                updateUsers(request,response);
                break;
            case "queryUser":
                queryUser(request,response);
                break;
        }
    }

    /**
     * 修改数据
     * @param request
     * @param response
     */
    private void updateUsers(HttpServletRequest request, HttpServletResponse response) {
        User user = WebUtils.getBean(User.class, request);
       /* String path = WebUtils.uploadFile(request, "newPic");
        //如果path是空，新的图片没上传，不做修改
        user.setPic(path==null?user.getPic():path);*/

        String password = user.getPassword();
        if (password != null && !password.equals("")) {
            //密码不为空的时候，证明用户修改过密码，重新设置密码
            //设置盐值
            user.setSalt(WebUtils.getRandomString());
            //重新设置密码
            user.setPassword(EncryptCodeUtils.getEncryptStr(user.getPassword(),
                    user.getSalt()));
        } else {
            //通过用户名重新查询一遍用户，得到这个密码和盐值
//            User queryUser = userService.queryUserByUsername(user.getUsername());
            User queryUser=userService.queryUserByUsername(user.getUsername());
            //设置密码
            user.setPassword(queryUser.getPassword());
            //重新设置盐值
            user.setSalt(queryUser.getSalt());
        }

        //修改
        boolean result = userService.updateUser(user);
        User loginUser = (User) request.getSession().getAttribute("username");

       /* if (result && loginUser.getId() == user.getId()) {
            request.getSession().setAttribute("user", user);
        }
*/
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");

        request.getSession().setAttribute("msg", result?"修改成功":"修改失败");
        request.getSession().setAttribute("result", result);


        try {
            response.sendRedirect("user?method=queryUsers&pn="+(pm==null?"":pm.getPn()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询单个用户数据
     */
    private void queryUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        User user = userService.queryUser(id);
        request.setAttribute("user", user);
        request.setAttribute("outerLi", "user");
        request.setAttribute("innerLi", "showUser");
        WebUtils.toRequestPage(request, response, "updateUsers");
    }
    /**
     * 删除数据
     * @param request
     * @param response
     */
    private void delUsers(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()-1);
            pm.setPages();
            //删除之后，正好最后一页没了，直接使用最后一页当作当前页
            pm.setPn(pm.getPn()>=pm.getPages()?pm.getPages():pm.getPn());
        }
        boolean result = userService.delUser(id);
        request.getSession().setAttribute("msg", result?"删除成功":"删除失败");
        request.getSession().setAttribute("result", result);
        try {
            response.sendRedirect("user?method=queryUsers&pn="+((pm==null)?"":pm.getPn()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 增加数据
     * @param request
     * @param response
     * @throws IOException
     */
    private void addUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user=WebUtils.getBean(User.class,request);
        user.setSalt(WebUtils.getRandomString());//设置盐值
        user.setPassword(EncryptCodeUtils.getEncryptStr(user.getPassword(),user.getSalt()));//设置加密后的密码
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()+1);
            pm.setPages();
        }

        boolean result = userService.addUser(user);
        request.getSession().setAttribute("msg", result?"增加成功":"增加失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("user?method=queryUsers&pn="+(pm==null?"":pm.getPages()));
    }


    /**
     * 查询所有数据
     */
    private void queryUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        List<User> users = userService.queryUsers(pm);
        int totalCount = userService.queryUserTotalCount();
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数

        request.setAttribute("users", users);
        request.getSession().setAttribute("pm", pm);
        request.setAttribute("outerLi", "user");
        request.setAttribute("innerLi", "showUser");
        WebUtils.toRequestPage(request, response, "showUsers");
    }
}
